var express = require('express');
var router = express.Router();
var core = require('core');
var wechat = core.wechat;
var qrlength = {
    max : 0,
    min : 0
};

core.api("open/qrcode",{
    time : 0,
    type : "count"
}, function(err, doc){
    qrlength.max = doc.docs;
});

core.api("open/qrcode",{
    time : JSON.stringify({$gt: 0}),
    type : "count"
}, function(err, doc){
    qrlength.min = doc.docs;
});

router.get('/', function(req, res, next){
    res.render('qrcode/index', {});
});

router.get('/add', function(req, res, next){
    res.render('qrcode/add', {});
});

router.get('/list', function(req, res, next){
    core.api("open/qrcode", {type: "get"}, function(err, doc){
        res.send(doc.docs);
    });
});


router.post('/add', function(req, res, next){
    var body = req.body;
    var time = body.time || 2592000;
    var action_name = time > 0 ? "QR_SCENE" : "QR_LIMIT_SCENE";
    var type = action_name === "QR_SCENE" ? "min" : "max";
    var msg = body.msg;
    var params = {
        "expire_seconds" : parseInt(time),
        "action_name": action_name,
        "action_info": {"scene": {"scene_id": qrlength[type] + 1}}
    };
    console.log(wechat.config.accessToken, params);
    wechat.api.post("cgi-bin/qrcode/create?access_token="+wechat.config.accessToken, params, "json", function(err, body){
        console.log(err, body,'============');
        qrlength[type] += 1;
        var params = {
            type: "set",
            qid : qrlength[type],
            time : time,
            url : body.url,
            ticket : body.ticket,
            msg : msg
        };
        core.api("open/qrcode", params, function(err, docs){
            console.log(err, docs,'-----------');
            // res.render('qrcode/index', {});
            res.redirect("/qrcode/list");
        });
    });
});

module.exports = router;
